package org.jeecg.modules.sggg.controller;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.sggg.entity.SgGoods;
import org.jeecg.modules.sggg.entity.SgGoodsRotation;
import org.jeecg.modules.sggg.entity.SgMember;
import org.jeecg.modules.sggg.entity.SgOperationRecords;
import org.jeecg.modules.sggg.service.ISgGoodsService;
import org.jeecg.modules.sggg.service.ISgMemberService;
import org.jeecg.modules.sggg.service.ISgOperationRecordsService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: 商品信息表
 * @Author: jeecg-boot
 * @Date: 2023-03-30
 * @Version: V1.0
 */
@Api (tags = "商品信息表")
@RestController
@RequestMapping ("/goods/sgGoods")
@Slf4j
public class SgGoodsController extends JeecgController<SgGoods, ISgGoodsService> {
    @Autowired
    private ISgGoodsService sgGoodsService;
    @Autowired
    private ISgMemberService sgMemberService;

    @Autowired
    private ISgOperationRecordsService sgOperationRecordsService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ISysDepartService sysDepartController;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 分页列表查询
     *
     * @param sgGoods
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "商品信息表-分页列表查询")
    @ApiOperation (value = "商品信息表-分页列表查询", notes = "商品信息表-分页列表查询")
    @GetMapping (value = "/list")
    public Result<IPage<SgGoods>> queryPageList (SgGoods sgGoods,
                                                 @RequestParam (name = "pageNo", defaultValue = "1") Integer pageNo,
                                                 @RequestParam (name = "pageSize", defaultValue = "10") Integer pageSize,
                                                 HttpServletRequest req) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String roleCode = redisUtil.get("roleCode:" + sysUser.getId()).toString();
        SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
        QueryWrapper<SgGoods> queryWrapper = QueryGenerator.initQueryWrapper(sgGoods, req.getParameterMap()).eq("is_delete", 0);
        // 根据DeptAttr机构属性判断当前登录人属于哪个机构（三高之家、三高基地、三高中心）
        if(sysDepart !=null && sysDepart.getDeptAttr()!=null){
            SysUser sysUser1 = sysUserService.getById(sysUser.getId());
            // 1.三高之家
            if(sysDepart.getDeptAttr().equals("1")){
                queryWrapper.eq("sys_org_code", sysUser.getOrgCode().toString());
            }
            // 2.三高基地
            if(sysDepart.getDeptAttr().equals("2")){
                String[] array = sysUser1.getResponsibleAgency().split(",");
                List<String> responsibleAgencies = Arrays.asList(array);
                queryWrapper.in("sys_org_code", responsibleAgencies);
            }
            // 3.三高中心
            if(sysDepart.getDeptAttr().equals("3")){
                String[] array = sysUser1.getResponsibleAgency().split(",");
                List<String> responsibleAgencies = Arrays.asList(array);
                queryWrapper.in("sys_org_code", responsibleAgencies);
            }
        }else if(roleCode.contains("dept_manage") || roleCode.contains("admin")){
            queryWrapper.like("sys_org_code",sysUser.getOrgCode());

        }else{
            queryWrapper.eq("sys_org_code", sysUser.getOrgCode().toString());
        }
        Page<SgGoods> page = new Page<SgGoods>(pageNo, pageSize);
        IPage<SgGoods> pageList = sgGoodsService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @GetMapping ("/queryList")
    public Result<List<SgGoods>> queryList () {
        return Result.OK(sgGoodsService.list());
    }

    /**
     * 添加
     *
     * @param sgGoods
     * @return
     */
    @AutoLog (value = "商品信息表-添加")
    @ApiOperation (value = "商品信息表-添加", notes = "商品信息表-添加")
    //@RequiresPermissions("goods:sg_goods:add")
    @PostMapping (value = "/add")
    public Result<String> add (@RequestBody SgGoods sgGoods) {
        sgGoodsService.save(sgGoods);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param sgGoods
     * @return
     */
    @AutoLog (value = "商品信息表-编辑")
    @ApiOperation (value = "商品信息表-编辑", notes = "商品信息表-编辑")
    //@RequiresPermissions("goods:sg_goods:edit")
    @RequestMapping (value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit (@RequestBody SgGoods sgGoods) {
        sgGoodsService.updateById(sgGoods);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog (value = "商品信息表-通过id删除")
    @ApiOperation (value = "商品信息表-通过id删除", notes = "商品信息表-通过id删除")
    //@RequiresPermissions("goods:sg_goods:delete")
    @DeleteMapping (value = "/delete")
    public Result<String> delete (@RequestParam (name = "id", required = true) String id) {
        sgGoodsService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog (value = "商品信息表-批量删除")
    @ApiOperation (value = "商品信息表-批量删除", notes = "商品信息表-批量删除")
    //@RequiresPermissions("goods:sg_goods:deleteBatch")
    @DeleteMapping (value = "/deleteBatch")
    public Result<String> deleteBatch (@RequestParam (name = "ids", required = true) String ids) {
        this.sgGoodsService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "商品信息表-通过id查询")
    @ApiOperation (value = "商品信息表-通过id查询", notes = "商品信息表-通过id查询")
    @GetMapping (value = "/queryById")
    public Result<SgGoods> queryById (@RequestParam (name = "id", required = true) String id) {
        SgGoods sgGoods = sgGoodsService.getById(id);
        if (sgGoods == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sgGoods);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param sgGoods
     */
    //@RequiresPermissions("goods:sg_goods:exportXls")
    @RequestMapping (value = "/exportXls")
    public ModelAndView exportXls (HttpServletRequest request, SgGoods sgGoods) {
        return super.exportXls(request, sgGoods, SgGoods.class, "商品信息表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("goods:sg_goods:importExcel")
    @RequestMapping (value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel (HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SgGoods.class);
    }

    /**
     * TODO     商品上下架
     *
     * @param
     * @return
     * @author WangJie
     * @date 2023/3/31 9:10
     * @Exception
     */
    @AutoLog (value = "商品表-商品上下架")
    @ApiOperation (value = "商品表-商品上下架", notes = "商品表-商品上下架")
    @RequestMapping (value = "/isOnSale", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> isOnSale (@RequestBody SgGoods sgGoods) {
        sgGoods.setIsOnSale(sgGoods.getIsOnSale() == 0 ? 1 : 0);
        sgGoodsService.updateById(sgGoods);
        return Result.OK(sgGoods.getIsOnSale() == 0 ? "下架成功!" : "上架成功!");
    }

    /**
     * TODO     积分兑换商品
     *
     * @param
     * @return
     * @author WangJie
     * @date 2023/4/12 9:10
     * @Exception
     */
    @AutoLog (value = "商品表-积分兑换商品")
    @ApiOperation (value = "商品表-积分兑换商品", notes = "商品表-积分兑换商品")
    @GetMapping (value = "/goodsExchange")
    public Result<String> goodsExchange (@RequestParam (name = "memberId") String memberId, @RequestParam (name = "goodsId") String goodsId) {
        try {
            SgMember sgMember = sgMemberService.getOne(new QueryWrapper<SgMember>().eq("id", memberId).eq("del_flag", 0));
            if (sgMember == null) {
                return Result.error("您的账户信息异常,请稍后再试!");
            }
            SgGoods sgGoods = sgGoodsService.getOne(new QueryWrapper<SgGoods>().eq("id", goodsId).eq("is_delete", 0).eq("is_on_sale", 1));
            if (sgGoods == null) {
                return Result.error("该商品已下架!");
            }
            if (sgMember.getCurrency() <= sgGoods.getCurrency()) {
                return Result.error("健康币数量不够!");
            }
            if (sgGoods.getGoodsNumber() <= 0) {
                return Result.error("商品库存不足!");
            }
            sgGoods.setGoodsNumber(sgGoods.getGoodsNumber() - 1);
            sgGoods.setSales(sgGoods.getSales() + 1);
            sgGoodsService.updateById(sgGoods);
            sgMember.setCurrency(sgMember.getCurrency() - sgGoods.getCurrency());
            sgMemberService.updateById(sgMember);
            SgOperationRecords sgOperationRecords = new SgOperationRecords();
            sgOperationRecords.setMemberId(memberId);
            sgOperationRecords.setType(1);
            sgOperationRecords.setGoodsId(goodsId);
            sgOperationRecords.setNumber(sgGoods.getCurrency());

            //region 结束时间
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date());
            cal.add(Calendar.DATE, sgGoods.getEffectiveDays());
            Date newDate = cal.getTime();
            sgOperationRecords.setEndTime(newDate);
            //endregion
            sgOperationRecords.setIsMake(0);
            sgOperationRecords.setCode(random());
            sgOperationRecordsService.save(sgOperationRecords);
            return Result.OK("兑换成功!");
        } catch (Exception e) {
            return Result.OK("兑换异常,请稍后再试!");
        }
    }

    /**
     * 根据机构获取商品信息
     *
     * @param orgCode
     * @return
     */
    @GetMapping("/getGoodsByOrgCode")
    public Result<List<SgGoods>> getGoodsByOrgCode(String orgCode) {
        List<SgGoods> sgGoods = sgGoodsService.list(new QueryWrapper<SgGoods>().eq("sys_org_code", orgCode));
        return Result.ok(sgGoods);
    }

    private String random() {

        int codeLength = 10;
        // 兑换码字符池（可根据自己的需要修改）
        String codePool = "ABCDEFGHJKMNPQRSTUVWXYZ23456789";

        // 生成兑换码的StringBuilder对象
        StringBuilder code = new StringBuilder();

        // 随机数生成器
        Random random = new Random();

        // 循环生成随机字符，直到生成足够长度的兑换码
        for (int i = 0; i < codeLength; i++) {
            int index = random.nextInt(codePool.length());
            char c = codePool.charAt(index);
            code.append(c);
        }
        return code.toString();
    }

}
